package com.csjbot.csjbase.base;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.csjbot.csjbase.event.BusFactory;
import com.csjbot.csjbase.event.IBus;
import com.csjbot.csjbase.kit.KnifeKit;
import com.csjbot.csjbase.log.Csjlogger;

import butterknife.Unbinder;

/**
 * Copyright (c) 2016, SuZhou CsjBot. All Rights Reserved.
 * www.csjbot.com
 * <p>
 * Created by 浦耀宗 at 2016/12/18 0018-13:48.
 * Email: puyz@csjbot.com
 */

public abstract class CsjBaseActivity extends AppCompatActivity implements UiCallback {

    protected Activity context;
    protected UiDelegate uiDelegate;
    private Unbinder unbinder;
    protected IBus ibus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.context = this;

        if (getLayoutId() > 0) {
            setContentView(getLayoutId());
            unbinder = KnifeKit.bind(this);

        }
        setListener();
        afterViewCreated(savedInstanceState);
    }

    protected UiDelegate getUiDelegate() {
        if (uiDelegate == null) {
            uiDelegate = UiDelegateBase.create(this);
        }
        return uiDelegate;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (useEventBus()) {
            ibus = BusFactory.getBus();
            ibus.register(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUiDelegate().resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        getUiDelegate().pause();
    }

    @Override
    protected void onStop() {
        if (useEventBus()) {
            if (ibus != null) {
                ibus.unregister(this);
            }
        }

        super.onStop();
    }

    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getUiDelegate().destory();
    }

    protected void postEvent(IBus.IEvent event) {
        if (ibus != null) {
            Csjlogger.debug("postEvent  " + event.getTag());
            ibus.post(event);
        }
    }

    protected void postSticky(IBus.IEvent event) {
        if (ibus != null) {
            ibus.postSticky(event);
        }
    }

}
